package org.zjx.app.task.tasks;


import org.zjx.app.commnad.ICommand;
import org.zjx.app.commnad.impl.*;
import org.zjx.app.task.Task;
import org.zjx.app.task.TaskMatcher;
import org.zjx.app.task.TaskType;
import org.zjx.command.entity.Pet;
import org.zjx.command.entity.Quest;
import org.zjx.command.entity.Sects;
import org.zjx.command.entity.screen.Address;
import org.zjx.command.entity.screen.Npc;
import org.zjx.command.entity.screen.Scene;
import org.zjx.command.enums.SlotType;
import org.zjx.command.state.*;
import org.zjx.data.GameSystem;

import java.util.ArrayList;
import java.util.List;

public class DivisionTask extends Task {
    private final Sects sects;

    public DivisionTask(Sects sect) {
        super("常规任务", "师门/师门任务", TaskType.RANDOM);
        totalReps = 20;
        this.sects = sect;
        initReceiveNpc();
    }

    public void initReceiveNpc() {
        npc = GameSystem.getInstance().getWorldManager().findNpc(sects.getMasterAddresses().get(0).getCity(),sects.getMasterName());
        dialogues = npc.getFunctions().get("师门任务");
    }

    @Override
    public List<String> getTemplates() {
        List<String> strings = new ArrayList<>();
        strings.add("任务完成，找师傅报告去。当前第{次数}次");
        strings.add("帮师傅送信给{NPC}，当前第{次数}次。");
        strings.add("在师门附近巡逻，当前第{次数}次。");
        strings.add("买到{道具}送给师傅，当前第{次数}次。");
        strings.add("帮师傅抓到{宠物名称}，当前第{次数}次。");
        return strings;
    }

    private int matchTemplate(String input) {
        if (input.isEmpty()) {
            return -1;
        }
        for (int i = 0; i < templates.size(); i++) {
            String template = templates.get(i);
            TaskMatcher.MatchResult matchResult = TaskMatcher.matchTask(template, input);
            if (matchResult.isMatched()) {
                return i; // 返回匹配的模板索引（从0开始）
            }
        }
        return -1; // 无匹配
    }


    @Override
    public ICommand getCommand(StateManager stateManager) {
        QuestState questState = stateManager.getState(QuestState.class);
        Quest quest = containsQuest(new ArrayList<>(questState.getQuests().values()));
        if (quest == null) {
            if (needRecover(stateManager)){
                return new RecoverCommand();
            }
            return new ClaimTaskCommand(npc, dialogues);
        }

        int index = matchTemplate(quest.getContent());
        if (index == 0) {
            return execute_0();
        } else if (index == 1) {
            return execute_1(quest);
        } else if (index == 2) {
            return execute_2(stateManager);
        } else if (index == 3) {
            return execute_3(stateManager,quest);
        } else if (index == 4) {
            return execute_4(stateManager,quest);
        }

//        //匹配错误,退出游戏
//        return new ExitCommand();
        return null;
    }

    private boolean needRecover(StateManager stateManager) {
        RoleState roleState = stateManager.getState(RoleState.class);
        PetState petState = stateManager.getState(PetState.class);
        if (roleState == null || petState == null) return false;
        if (roleState.getHpPercentage() < 51 || roleState.getMpPercentage() < 80) return true;
        Pet pet = petState.getPets().stream().filter(Pet::isWar).findFirst().orElse(null);
        if (pet == null) return false;
        return pet.getLoyal() < 70;
    }


    public ICommand execute_0() {
        return new DeliverTaskCommand(npc, dialogues);
    }

    public ICommand execute_1(Quest quest) {
        TaskMatcher.MatchResult result = TaskMatcher.matchTask(templates.get(1), quest.getContent());
        String npcName = "";  //npc名称
        String count = "";  //次数
        for (TaskMatcher.Keyword keyword : result.getKeywords()) {
            if (keyword.getPlaceholder().equals("NPC")) npcName = keyword.getKeyword();
            if (keyword.getPlaceholder().equals("次数")) count = keyword.getKeyword();
        }
        Npc npc = GameSystem.getInstance().getWorldManager().findNpc(npcName);
        return new GiveNpcItemCommand(npc, SlotType.QUEST_ITEMS, "书信");
    }

    private ICommand execute_2(StateManager stateManager) {
        Scene scene = GameSystem.getInstance().getWorldManager().getScene(sects.getMasterAddresses().get(0).getCity());
        return new PatrolCommand(scene, getSectsPoints(sects));
    }

    private ICommand execute_3(StateManager stateManager,Quest quest) {
        ItemState itemState = stateManager.getState(ItemState.class);
        TaskMatcher.MatchResult result = TaskMatcher.matchTask(templates.get(3), quest.getContent());
        String itemName = "";  //npc名称
        String count = "";  //次数
        for (TaskMatcher.Keyword keyword : result.getKeywords()) {
            if (keyword.getPlaceholder().equals("道具")) itemName = keyword.getKeyword();
            if (keyword.getPlaceholder().equals("次数")) count = keyword.getKeyword();
        }

        if (itemState == null || itemState.findItemsByTemplate(itemName).isEmpty()) {
            return new BuyItemCommand(itemName, 1);
        } else {
            return new GiveNpcItemCommand(npc, SlotType.INVENTORY, itemName);
        }
    }


    private ICommand execute_4(StateManager stateManager, Quest quest) {
        PetState petState = stateManager.getState(PetState.class);
        TaskMatcher.MatchResult result = TaskMatcher.matchTask(templates.get(4), quest.getContent());
        String itemName = "";  //npc名称
        String count = "";  //次数
        for (TaskMatcher.Keyword keyword : result.getKeywords()) {
            if (keyword.getPlaceholder().equals("宠物名称")) itemName = keyword.getKeyword();
            if (keyword.getPlaceholder().equals("次数")) count = keyword.getKeyword();
        }

        if (petState.havePetName(itemName)) {
            return new DeliverTaskCommand(npc, dialogues);
        }else if (petState.getCurrentSize() < petState.getMaxSize()) {
            return new AssociationCommand("宠物",itemName,8000);
        }else {
            throw new IllegalArgumentException("宠物栏已满");
        }
    }

    private List<Address> getSectsPoints(Sects sects) {
        List<Address> points = new ArrayList<>();
        switch (sects) {
            case HUA_GUO_SHAN:
                points.add(new Address("幻境花果山",20, 94));
                points.add(new Address("幻境花果山",9, 54));
                points.add(new Address("幻境花果山",33, 12));
                points.add(new Address("幻境花果山",115, 17));
                points.add(new Address("幻境花果山",111, 64));
                points.add(new Address("幻境花果山",56, 48));
                break;
            case DA_TANG_GUAN_FU:
                points.add(new Address("大唐官府",98, 36));
                points.add(new Address("大唐官府",57, 30));
                points.add(new Address("大唐官府",160, 62));
                points.add(new Address("大唐官府",17, 83));
                break;
            default:
                throw new IllegalArgumentException("门派" + sects.getName() + "巡逻点位未收录!!!");
        }
        return points;
    }


}
